<template>
<!--  订单管理-订单记录-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单签订时间" prop="orderTime"label-width="100px">
        <el-date-picker clearable
          v-model="queryParams.orderTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择订单签订时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:order:importOrder']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">

      <!--展开行表格-->
      <el-table-column type="expand">
        <template slot-scope="props" >
          <el-table :data="props.row.sysProdList" :row-class-name="expandColor" size="mini" style="width: 80%;margin-left: 7%;" >
            <el-table-column label="订单编号" prop="orderCode"></el-table-column>
            <el-table-column label="货物编码" prop="prodCode"></el-table-column>
            <el-table-column label="货物名称" prop="prodName"></el-table-column>
            <el-table-column label="订购数量" prop="quantity"></el-table-column>
            <el-table-column label="物品单位" prop="prodUnits"></el-table-column>
            <el-table-column label="物品单价" prop="prodPrice"></el-table-column>
            <el-table-column label="实到数量" prop="actualQuantity"></el-table-column>
            <el-table-column label="去皮数量" prop="decorticateQuantity"></el-table-column>
            <el-table-column label="毛重" prop="roughQuantity"></el-table-column>
            <el-table-column label="收货类型" prop="receiptType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_receipt_type" :value="scope.row.receiptType"/>
              </template>
            </el-table-column>
            <el-table-column label="预定时间" prop="scheduledTime" width="135px"></el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="订单签订时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="订单签订时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择订单签订时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">物品列信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSysProd">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSysProd">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="sysProdList" :row-class-name="rowSysProdIndex" @selection-change="handleSysProdSelectionChange" ref="sysProd">
          <el-table-column type="selection" width="50" align="center" />
<!--          <el-table-column label="序号" align="center" prop="index" width="50"/>-->
          <el-table-column label="货物编码" prop="prodCode" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.prodCode" placeholder="请输入货物编码" />
            </template>
          </el-table-column>
          <el-table-column label="货物名称" prop="prodName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.prodName" placeholder="请输入货物名称" />
            </template>
          </el-table-column>
          <el-table-column label="订购数量" prop="quantity" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入订购数量" />
            </template>
          </el-table-column>
          <el-table-column label="物品单位" prop="prodUnits" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.prodUnits" placeholder="请输入物品单位" />
            </template>
          </el-table-column>
          <el-table-column label="物品单价" prop="prodPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.prodPrice" placeholder="请输入物品单价" />
            </template>
          </el-table-column>
          <el-table-column label="预定时间" prop="scheduledTime" width="240">
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.scheduledTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择预定时间" />
            </template>
          </el-table-column>
<!--          <el-table-column label="实到数量" prop="actualQuantity" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.actualQuantity" placeholder="请输入实到数量" />-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="去皮数量" prop="decorticateQuantity" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.decorticateQuantity" placeholder="请输入去皮数量" />-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="收货类型" prop="receiptType" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.receiptType" placeholder="请输入收货类型" />-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importOrderTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/system/order";
import { getToken } from "@/utils/auth";

export default {
  name: "Order",
  dicts: ['sys_receipt_type'],
  data() {
    return {
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/order/importOrder"
      },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSysProd: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单记录表格数据
      orderList: [],
      // 物品列表格数据
      sysProdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        orderTime: null,
        scheduledTime: null,
        receiptType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderCode: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        orderTime: [
          { required: false, message: "订单签订时间不能为空", trigger: "blur" }
        ],
        prodCode: [
          { required: false, message: "货物编码不能为空", trigger: "blur" }
        ],
        prodName: [
          { required: false, message: "货物名称不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: false, message: "订购数量不能为空", trigger: "blur" }
        ],
        prodUnits: [
          { required: false, message: "物品单位不能为空", trigger: "blur" }
        ],
        prodPrice: [
          { required: false, message: "物品单价不能为空", trigger: "blur" }
        ],
        scheduledTime: [
          { required: false, message: "预定时间不能为空", trigger: "blur" }
        ],
        actualQuantity: [
          { required: false, message: "实到数量不能为空", trigger: "blur" }
        ],
        decorticateQuantity: [
          { required: false, message: "去皮数量不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单记录列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderCode: null,
        orderTime: null,
        prodCode: null,
        prodName: null,
        quantity: null,
        prodUnits: null,
        prodPrice: null,
        scheduledTime: null,
        actualQuantity: null,
        decorticateQuantity: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.sysProdList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    //展开行样式控制方法
    expandColor(){
      return 'warning-row'
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.sysProdList = response.data.sysProdList;
        this.open = true;
        this.title = "修改订单记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.sysProdList = this.sysProdList;
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单记录编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 物品列序号 */
    rowSysProdIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 物品列添加按钮操作 */
    handleAddSysProd() {
      let obj = {};
      obj.prodCode = "";
      obj.prodName = "";
      obj.quantity = "";
      obj.prodUnits = "";
      obj.prodPrice = "";
      obj.scheduledTime = "";
      obj.actualQuantity = "";
      obj.decorticateQuantity = "";
      obj.remark = "";
      this.sysProdList.push(obj);
    },
    /** 物品列删除按钮操作 */
    handleDeleteSysProd() {
      if (this.checkedSysProd.length == 0) {
        this.$modal.msgError("请先选择要删除的物品列数据");
      } else {
        const sysProdList = this.sysProdList;
        const checkedSysProd = this.checkedSysProd;
        this.sysProdList = sysProdList.filter(function(item) {
          return checkedSysProd.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSysProdSelectionChange(selection) {
      this.checkedSysProd = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_export_template_${new Date().getTime()}.xlsx`)
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "订单导入";
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importOrderTemplate() {
      this.download('/system/order/importOrderTemplate', {
      }, `order_import_template_${new Date().getTime()}.xlsx`)
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  },

};
</script>
<style type="text/css">
  .el-table .warning-row {
    background: oldlace;
  }
</style>
